package com.jhgsys.internal.formDesign.controller.upload;

import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.constant.FileUploadConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.common.utils.ImageUtils;
import com.jhgsys.internal.common.utils.Plupload;
import com.jhgsys.internal.common.utils.UploadPathUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author fenghaijun
 */
@Controller()
public class formDesignUploadController {

    public static String MSG_ERROR_FILE_TYPE = "文件类型不正确！";
    public static String MSG_ERROR_NO_FILE = "未包含上传文件！";
    // 文件允许格式
    private static final String[] allowImageFiles = {".gif", ".png", ".jpg", ".jpeg", ".bmp" };
    private static final String[] allowVideoFiles = {".swf", ".wmv", ".mpg", ".m4v", ".mp4", ".flv", ".3gp", ".avi", ".rmvb", ".mkv"};
    private static final String[] allowOtherFiles = {".rar", ".zip", ".pdf", ".txt", ".ppt", ".pptx", ".doc", ".docx", ".xls", ".xlsx" };

    @Log("自定义表单上传附件")
    @PostMapping("formDesign/upload")
    @ResponseBody
    public FebsResponse upload(@RequestParam("file") MultipartFile file) {
        if (!checkFileType(file.getOriginalFilename(), allowImageFiles)
                &&!checkFileType(file.getOriginalFilename(), allowVideoFiles)
                &&!checkFileType(file.getOriginalFilename(), allowOtherFiles)) {
            return new FebsResponse().fail().message(MSG_ERROR_FILE_TYPE);
        }
        String path = FileUploadConstant.FORM_DESIGN_FILE_PATH;
        FebsResponse objects = fileUpCommon(file, path);
        return objects;
    }

    public static FebsResponse fileUpCommon(MultipartFile file, String path) {
        try {
            String fileId = FebsUtil.uuid();
            String name = file.getOriginalFilename();
            path = path + "/" + dateFormat();
            assert name != null;
            String suffixName = name.substring(name.lastIndexOf("."));
            String fileName = fileId + suffixName;
//            String fileDir = "/" +path ;
            String fileRelPath = "/" + path + '/'  + fileName;
            String absolutePath = UploadPathUtil.getRootPath() + path+ '/' ;
            String absolutePathSmall = absolutePath + "small/";
            File filepath = new File(absolutePath,fileName);
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            file.transferTo(filepath);

            if (checkFileType(file.getOriginalFilename(), allowImageFiles)){
                ImageUtils.zoomImage(absolutePath + fileName , absolutePathSmall + fileName, 200, 0);
            }
            Map<String, Object> data = new HashMap<>();
            data.put("fileName", file.getOriginalFilename());
            data.put("filePath", "files" + fileRelPath);
            data.put("smallPath", absolutePathSmall+ fileName);
            return new FebsResponse().success().data(data);

        } catch (Exception e) {
            return new FebsResponse().fail().message("文件上传失败！Error：" + e.getMessage());
        }
    }

    private static String dateFormat() {
        String formatDay = DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd");
        return formatDay;
    }

    /**
     * 文件类型判断
     *
     * @param fileName
     * @return
     */
    private static boolean checkFileType(String fileName, String[] allowFiles) {
        Iterator<String> type = Arrays.asList(allowFiles).iterator();
        while (type.hasNext()) {
            String ext = type.next();
            if (fileName.toLowerCase().endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

}
